import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ChannelManageService } from '../../../shared/services/channel.service';
import { UtilsService } from '../../../shared/services/utils.service';

import {environment} from '../../../../environments/environment';

let uploadSwitch = false;
@Component({
  selector: 'app-channel-manage',
  templateUrl: './channel-manage.component.html',
  styleUrls: ['./channel-manage.component.scss']
})
export class ChannelManageComponent implements OnInit {

  validateForm: FormGroup;

  confirmModal: any;

  _value = '';
  isVisible = false;    // alert
  _allChecked = false;
  _loading = false;
  _indeterminate = false;
  _displayData = [];

  _options: any;

  fileList = [];
  previewImage = '';
  previewVisible = false;

  channel: any;
  channelAlert: any;
  userType: String;
  modalType: String;
  deleteArr: Array<Number> = [];

  data = [];

  expandDataCache = {};

  fileUrl: String = '';

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private modal: NzModalService,
    private _message: NzMessageService,
    private fb: FormBuilder,
    private utilsService: UtilsService,
    private channelService: ChannelManageService,
  ) {}

  ngOnInit() {
    this.fileUrl = environment.apiBaseUrl + 'admin/file/upload';
    this.validateForm = this.fb.group({
      formLayout: [ 'horizontal' ],
      materialName : [ null, [ Validators.required ] ],
      dosageSelect : [ null ],
      materialOrder : [ null ],
      newLabelName : [ null ]
    });
    this.reset();
    this.resetAlert();
    this.getChannel();
    // 获取所有渠道
    this.getChannelTreeid('');
  }

  // 获取一级渠道
  getChannel(type: String = 'create'): void {
    this._loading = true;
    this.channelService.getChannel(this.channel)
        .subscribe(res => {
          console.log(res);
          if (res['code'] === '0') {
            this.channel.pageNumber = res['data']['pageNumber'];
            this.channel.totalPages = res['data']['totalPages'] * this.channel.pageSize;
            this.data = res['data']['list'];
            this.data.forEach((item, index) => {
              this.expandDataCache[ item.id ] = this.convertTreeToList(item);
            });
            if (type === 'update') {
              this._message.success('数据已更新', {nzDuration: 2000});
            }
          } else {
            this._message.error('数据请求错误,' + res['msg'], {nzDuration: 2000});
          }
          if (this._loading) {
            this._loading = false;
          }
        });
  }

  // 设置可选级,
  // s: 要显示的级别 3,2,1...
  setSelectTrue(array, pa) {
    const s = 0;
    function mapArray(arr, si) {
      si++;
      arr.forEach(item => {
        if (si > pa) {
          item['disabled'] = true;
        }
        if (item.children) {
          if (item.children.length > 0) {
              mapArray(item.children, si);
          }
        }
      });
    }
    mapArray(array, s);
  }

  // 获取所有渠道
  getChannelTreeid(callbacl) {
    this.channelService.getChannelTree()
        .subscribe(res => {
          // console.log('获取所有渠道', res);
          if (res['code'] === '0') {
            this.channelAlert.data = res['data'];
            this.setSelectTrue(this.channelAlert.data, 2);
            if (callbacl) {
              callbacl();
            }
          }
        });
  }

  // 选择上级,取最后一个id
  _console(value) {
    // console.log(value);
    if (value) {
      this.channelAlert.parentId = value.option.id;
    }
  }

  reset() {
    this.channel = {
      channelName: '',
      pageNumber: 1,    // 分页参数,请求第几页,不传参默认为1
      pageSize: 10,      // 分页参数，每页多少条记录，不传参默认为20
      totalPages: 0,    // 总页数
      data: '',         // 一级渠道list  -> children  子渠道
    };
  }

  resetAlert() {
    this.channelAlert = {
      id: '',
      data: '',
      name: '',
      order: '',
      parentId: '',
      imagePath: '',
    };
  }

  collapse(array, data, $event) {
    if ($event === false) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.id === d.id);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [], array = [], hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[ i ], level: node.level + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[ node.id ]) {
      hashMap[ node.id ] = true;
      array.push(node);
    }
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
  }

  get isHorizontal() {
    return this.validateForm.controls[ 'formLayout' ] && this.validateForm.controls[ 'formLayout' ].value === 'horizontal';
  }

  onSearch(event: string): void {
    this.reset();
    this.channel.channelName = event;
    this.getChannel('update');
  }

  _displayDataChange($event) {
    this._displayData = $event;
  }

  // 分页搜索
  _refreshStatus(reset = false) {
    if (reset) {
      this._allChecked = false;
      this._indeterminate = false;
      this.getChannel('update');
    }
  }

  // 全选
  _checkAll(value) {
    if (value) {
      this.mapArraySet(this.data, true);
    } else {
      this.mapArraySet(this.data, false);
    }
    const dataArr = this.concatObjDataToArray(this.data);
    this.dataApply(dataArr);
  }

  _checkedInput($event, parent) {
    const that = this;
    // console.log($event.checked);
    this._indeterminate = $event.checked;
    parent.indeterminate = $event.checked;
    // 判断他下级是否存在
    const dataArr = this.concatObjDataToArray(this.data);
    dataArr.find(i => i['id'] === $event['id'])['checked'] = $event.checked;
    if ($event['children']) {
      // console.log('children');
      this.mapArraySet($event['children'], $event.checked);
      // 改变状态
      const eventChildren = this.concatObjDataToArray($event['children']);
      dataArr.forEach(item => {
        eventChildren.forEach(ite => {
          if (item['id'] === ite['id']) {
            item['checked'] = ite['checked'];
          }
        });
      });
    }
    // 渲染数组
    this.dataApply(dataArr);
    // 全选有待解决
    const allChecked = this.data.every(value => value.checked === true);
    const allUnChecked = this.data.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = !allChecked && !allUnChecked;
  }

  // 递归遍历数组赋值
  mapArraySet(array, bool) {
    const that = this;
    array.forEach(item => {
      item['checked'] = bool;
      if (item.children) {
        if (item.children.length > 0) {
          that.mapArraySet(item.children, bool);
        }
      }
    });
  }

  // 把对象组合成数组
  concatObjDataToArray(array) {
    const that = this;
    const concatArr = [];
    function mapArray(arr) {
      arr.forEach(item => {
        concatArr.push(item);
        if (item.children) {
          if (item.children.length > 0) {
            mapArray(item.children);
          }
        }
      });
    }
    mapArray(array);
    return concatArr;
  }

  // 表格数据跟 data 数据 apply
  dataApply(array) {
    const that = this;
    array.forEach(item => {
      for (const ide in that.expandDataCache) {
        that.expandDataCache[ide].forEach(ite => {
          if (ite['id'] === item['id']) {
            ite['checked'] = item['checked'];
          }
        });
      }
    });
  }

  // 跳转新增页
  locationAddMaterial() {
    this.router.navigate(['./add'], {
      relativeTo: this.route
    });
  }

  // 弹窗操作
  showModal = (type, item) => {
    const that = this;
    this.getChannelTreeid(() => {
      that.modalType = type;
      if (type === 'create') {
        that.channelAlert['name'] = '';
        that.channelAlert['order'] = '';
        that.channelAlert['imagePath'] = '';
        that.channelAlert['parentId'] = '';
        that.fileList = [];
        that._options = null;
      } else {
        // console.log('弹出面料选择弹窗', item);
        that.channelAlert['id'] = item['id'];
        that.channelAlert['name'] = item['name'];
        that.channelAlert['order'] = item['order'];
        that.channelAlert['imagePath'] = item['imagePath'];
        that.channelAlert['parentId'] = item['parentId'];
        that.channelAlert['parentName'] = item['parentName'];
        // 一级
        // that._options = that.channelAlert['parentId'];
        // 级联
        setTimeout(() => {
          that._options = [
            {
              id: item['parentId'],
              name: item['parentName']
            }
          ];
        }, 10);
        // console.log(that._options);
        if (item['imagePath']) {
          // console.log('img: ', item['imagePath']);
          const imgName = item['imagePath'].substr(item['imagePath'].lastIndexOf('/') + 1);
          that.fileList = [{
            uid: -1,
            name: imgName,
            status: 'done',
            url: item['imagePath'],
            thumbUrl: item['imagePath'],
          }];
        } else {
          // 写入默认图片
          that.fileList = [{
            uid: -1,
            name: '404.png',
            status: 'done',
            url: './assets/images/df.png',
            thumbUrl: './assets/images/df.png',
          }];
        }
      }
      that.isVisible = true;
    });
  }

  // 新增
  handleOk = (e) => {
    // 必须填写渠道名称
    if (!this.channelAlert['name']) {
      this._message.error(`操作失败，必须填写渠道名称`, {nzDuration: 3000});
      return false;
    }
    if (this.channelAlert['name'].length > 20) {
      this._message.error(`渠道名称必须小于20个字符`, {nzDuration: 3000});
      return false;
    }
    // 判断必须上传图片
    // if (!this.channelAlert['imagePath']) {
    //   this._message.error(`操作失败，必须上传图片`, {nzDuration: 3000});
    //   return false;
    // }
    // 删除图片,清空 imagePath,
    if (this.fileList.length < 1) {
      this.channelAlert.imagePath = '';
    }
    if (this.modalType === 'create') {
      this.channelService.postCreateChannel(this.channelAlert)
        .subscribe(res => {
          // console.log(res);
          if (res['code'] === '0') {
            this._message.success('渠道新增成功', {nzDuration: 2000});
            this.getChannel('update');
          } else {
            this._message.error(`渠道新增失败，${res['msg']}`, {nzDuration: 3000});
          }
        });
    } else {
      if (Object.prototype.toString.call(this.channelAlert.parentId) === '[object Object]') {
        this.channelAlert.parentId = this.channelAlert.parentId['id'];
      }
      this.channelService.postUpdateChannel(this.channelAlert)
        .subscribe(res => {
          // console.log(res);
          if (res['code'] === '0') {
            this._message.success('渠道更新成功', {nzDuration: 2000});
            this.getChannel();
          } else {
            this._message.error(`渠道更新失败，${res['msg']}`, {nzDuration: 3000});
          }
        });
    }
    this.isVisible = false;
  }

  handleCancel = (e) => {
    // console.log(e);
    this.channelAlert['name'] = '';
    this.channelAlert['order'] = '';
    this.channelAlert['imagePath'] = '';
    this.channelAlert['parentId'] = '';
    this._options = '';
    this.isVisible = false;
  }

  handlePreview = (file) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  // 刷新
  update(): void {
    this.reset();
    this.getChannel('update');
  }

  // 删除
  delete(obj) {
    // console.log(obj);
    const that = this;
    this.deleteArr = [];
    if (obj) {
      this.deleteArr.push(obj['id']);
    } else {
      // console.log(this.expandDataCache);
      for (const ide in that.expandDataCache) {
        that.expandDataCache[ide].forEach(ite => {
          if (ite['checked']) {
            that.deleteArr.push(ite['id']);
          }
        });
      }
    }
    if (this.deleteArr.length < 1) {
      return false;
    }
    this.channelService.postDeleteChannel(this.deleteArr)
        .subscribe(res => {
          // console.log(res);
          if (res['code'] === '0') {
            this._message.success('渠道删除成功', {nzDuration: 2000});
            this.getChannel();
          } else {
            this._message.error(`渠道删除失败，${res['msg']}`, {nzDuration: 4000});
          }
        });
  }

  upload({ file, fileList }): void {
    // console.log({ file, fileList });
    if (!uploadSwitch) {
      uploadSwitch = true;
      setTimeout(() => {
        uploadSwitch = false;
      }, 3000);
      const param = {
        fileType: 'image',
        file: file['originFileObj']
      };
      this.utilsService.postUploadFiles(param)
          .subscribe(res => {
            // console.log(res);
            if (res['state'] === 'SUCCESS') {
              this.channelAlert.imagePath = res['url'];
            }
          });
    }
  }

  // 超过最大字数红报错
  changeName(item) {
    if (item.name.length > 20) {
      item.nameErr = true;
    } else {
      item.nameErr = false;
    }
  }

}
